/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import model.Item;
import model.ItemModel;
import model.Panier;

/**
 *
 * @author alocubiche
 */
public class MainController extends HttpServlet {
    private Panier panier = new Panier();

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            /* TODO output your page here. You may use following sample code. */
            out.println("<!DOCTYPE html>");
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet MainController</title>");            
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet MainController at " + request.getContextPath() + "</h1>");
            out.println("</body>");
            out.println("</html>");
            /*switch(request. ){
             * }
             */
        } finally {            
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        try {
            /* TODO output your page here. You may use following sample code. */
            out.println("<!DOCTYPE html>");
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet MainController</title>");            
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>GET Main Controller at " + request.getContextPath() + "</h1>");
            out.println(request.getParameter("itemId"));
            out.println("</body>");
            out.println("</html>");
        } finally {            
            out.close();
        }
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException 
    {
        PrintWriter out = response.getWriter();
        if (request.getParameter("action").equals("addItem"))
        {
            //Ajouter un article à la base
            ItemModel.InsertOne(request.getParameter("itemName"),Integer.parseInt(request.getParameter("itemPrice")),Integer.parseInt(request.getParameter("itemQuantity")));
            
            HttpSession session = request.getSession(true);
            String message = null;
            message = "<br /><h3><font color=\"red\">Article ajouté</font></h3>";
            session.setAttribute("message", message);
            
            RequestDispatcher disp = this.getServletContext().getRequestDispatcher("/index.jsp");
            disp.forward(request, response);
        }
        
        if (request.getParameter("action").equals("itemList"))
        {
            
            //Lister les articles de la base
            ArrayList<Item> articles = null;
            HttpSession session = request.getSession(true);
            articles = ItemModel.selectAll();
            session.setAttribute("articles", articles);
            session.setAttribute("message", null);
            System.out.println(articles.size() + " articles sélectionnés");
            RequestDispatcher disp = this.getServletContext().getRequestDispatcher("/itemList.jsp");
            disp.forward(request, response);
        }
        if (request.getParameter("action").equals("Buy"))
        {
            //Ajouter un/des article(s) au panier
            String[] selection = request.getParameterValues("id");
            String[] selectionQuantite = request.getParameterValues("idQuantity");
            
            for(int i = 0; i < selection.length; i++)
            {
             if (selectionQuantite[i].equals("0")!= true)
             {
                //Pour chaque article sélectionnée, l'ajouter au panier
                Item article = ItemModel.selectOne(Integer.parseInt(selection[i]),Integer.parseInt(selectionQuantite[i]));//Récupère l'article
                panier.addItem(article);
             }
            }
            
            //Envoi du panier à la page JSP
            HttpSession session = request.getSession(true);
            session.setAttribute("message", null);
            Panier panierBean = null;
            panierBean = (Panier) session.getAttribute("panier");
            panierBean = panier;
            session.setAttribute("panier", panierBean);
            
            /*if (panierBean==null)
            {
                panierBean = panier;
                session.setAttribute("panier", panierBean);
            }*/
            RequestDispatcher disp = this.getServletContext().getRequestDispatcher("/order.jsp");
            disp.forward(request, response);
        }
        if (request.getParameter("action").equals("Remove"))
        {
            String[] selection = request.getParameterValues("id");
            String[] selection2 = request.getParameterValues("idQuantity");
            
            if (selection != null)
            {
                for(int i = 0; i < selection.length; i++)
                {
                   //Pour chaque article sélectionnée, suppression du panier
                   Item article = ItemModel.selectOne(Integer.parseInt(selection[i]),Integer.parseInt(selection2[i]));//Récupère l'article
                   panier.removeItem(article);
                   System.out.println(article.getName() + " a été retiré du panier - V"); 
                
                }
            }
                
            
            //Envoi du panier à la page JSP
            HttpSession session = request.getSession(true);
            session.setAttribute("message", null);
            Panier panierBean = null;
            panierBean = panier;
            session.setAttribute("panier", panierBean);
            /*if (panierBean==null)
            {
                panierBean = panier;
                session.setAttribute("panier", panierBean);
            }*/
            RequestDispatcher disp = this.getServletContext().getRequestDispatcher("/index.jsp");
            disp.forward(request, response);
        }
        out.close();
        //processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
